package com.edt.ichannel.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;


public class BeanUtils {
	
	private static Logger logger = LoggerFactory.getLogger(BeanUtils.class);
	
	
	
	
	/**
	 * @描述 Object to map 将所有字段及字段值封装至MAP  KEY转小写 值为NULL 传 “”
	 * @return
	 */
	public static Map<String,String> obj2MapKeytoLowerCase(Object obj){
		Map<String,String> map = new HashMap<String, String>();
		
		try {
			Field[] fields = obj.getClass().getDeclaredFields();
			for(Field filed :fields){
				filed.setAccessible(true);
				String filedName = filed.getName();
				String filedValue = filed.get(obj)==null?"":filed.get(obj).toString();
				map.put(filedName.toLowerCase(), filedValue);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return map;
		}
		
		return map;
		
	}
	
	/**
	 * @描述 Object to map 将所有字段及字段值封装至MAP  值为NULL 传 “”
	 * @return
	 */
	public static Map<String,String> obj2Map(Object obj){
		Map<String,String> map = new HashMap<String, String>();
		
		try {
			
			Field[] fields = obj.getClass().getDeclaredFields();
			for(Field filed :fields){
				filed.setAccessible(true);
				String filedName = filed.getName();
				String filedValue = filed.get(obj)==null?"":filed.get(obj).toString();
				map.put(filedName, filedValue);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return map;
		}
		
		return map;
		
	}
	
	/***
	 *将 REQUEST 转换为 实体BEAN
	 *
	 * @param request
	 * @throws NoSuchMethodException
	 * @throws SecurityException
	 */
	public  static <T> T request2Bean(Class<T> beanClazz, HttpServletRequest request) {
		System.out.println("==========Requst parameters Start========");
		Enumeration<?> names = request.getParameterNames();
		while(names.hasMoreElements()){
			String name = (String) names.nextElement();
			Object value = request.getParameter(name);
			System.out.println(name +"=[" + value+"]");
		}
		System.out.println("==========Requst parameters End========");
		
		Object obj = null;
		try {
			obj = beanClazz.newInstance();
			Field[] fields = obj.getClass().getDeclaredFields();
			for (int i = 0; i < fields.length; i++) {
				String fieldName = fields[i].getName();
				Class<?> type = fields[i].getType();
				//Type gType = fields[i].getGenericType();
				// 处理set 方法 interfaceVersion --> setInterfaceVersion(String );
				String indexFieldName = fieldName.substring(0, 1).toUpperCase();
				// 组装 set方法
				String setfieldName = "set" + indexFieldName + fieldName.substring(1);
				
				Method method = null;
				try {
					//如遇此方法 不存在直接跳出 忽略此方法
					method = obj.getClass().getMethod(setfieldName, type);
				} catch (NoSuchMethodException e) {
					logger.warn("setfieldName:" + setfieldName +" 方法不存在！");
					continue;
				}
				
				String value =  request.getParameter(fieldName);
				//如何值为空，不执行方法
				if(null == value || "".equals(value)){
					continue;
				}
				Object objVlue = castType(value,type);
				logger.info(fieldName+":obj value:[" + value+"]");
				method.invoke(obj, objVlue);
			}
		
		} catch (InstantiationException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IllegalAccessException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return (T) obj;
	}
	
	
	/**
	 * 数据类型转换
	 * @param obj
	 * @param clazz
	 * @return
	 * @throws IllegalAccessException
	 * @throws InstantiationException
	 * @throws NumberFormatException
	 */
	private static Object castType(Object obj, Class<?> clazz) {
		try {
			//System.out.println("obj:" + obj + "  clazz:"+ clazz.toString());
			if(null == obj){
				return null;
			}
			
			if(clazz.equals(int.class)){
				return  Integer.parseInt(obj.toString());
			}else if(clazz.equals(float.class)){
				return  Float.parseFloat(obj.toString());
			}else if(clazz.equals(char.class)){
				return  (Character)obj;
			}else if(clazz.equals(short.class)){
				return  Short.valueOf(obj.toString());
			}else if(clazz.equals(byte.class)){
				return  Byte.valueOf(obj.toString());
			}else if(clazz.equals(long.class)){
				return  Long.valueOf(obj.toString());
			}else if(clazz.equals(double.class)){
				return  Double.valueOf(obj.toString());
			}else if(clazz.equals(Integer.class)){
				return  Integer.parseInt(obj.toString());
			}
			
			
			Object newObj = clazz.newInstance();
			if(newObj instanceof String){
				return  obj+"";
			}else if(newObj instanceof Boolean){
				return  Boolean.valueOf(obj.toString());
			}else if(newObj instanceof Long){
				return  Long.getLong(obj.toString());
			}else if(newObj instanceof Double){
				return  Double.valueOf(obj.toString());
			}else{
				return obj;
			}
		} catch (Exception e) {
			logger.error(clazz +"是基本数据类型无法强转，【"+e.getMessage()+"】");
			e.getMessage();
			return obj;
		}
	}
	
	/**
	 * Map 转实体
	 * @param map
	 * @param clazz
	 * @return
	 */
	public static <T> T map2Bean(Map<String,Object> map , Class<T> clazz){
		
		Object obj = null;
		try {
			obj = clazz.newInstance();
			Iterator<String> iterator = map.keySet().iterator();
			
			while(iterator.hasNext()){
				String key = iterator.next();
				String methodName = "";
				try {
					Field field = /*clazz.getField(key);*/clazz.getDeclaredField(key);
					Class type = field.getType();
					String indexName = key.substring(0, 1).toUpperCase();
					methodName  = "set" + indexName + key.substring(1);
					Method method = clazz.getMethod(methodName, type);
					Object valueObj = castType(map.get(key),type);
					method.invoke(obj, valueObj);
				} catch (SecurityException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (NoSuchMethodException e) {
					logger.warn(methodName + "方法未找到 ....");
					break;
				} catch (IllegalArgumentException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (InvocationTargetException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (NoSuchFieldException e) {
					logger.warn(key + "字段未找到 ....");
					break;
				}
			}
			
			
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return (T) obj;
	}
	
}